import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { CharacterManager } from '../game/Character'

export interface GameSettings {
  soundEnabled: boolean
  musicEnabled: boolean
  masterVolume: number
  controlScheme: 'keyboard' | 'touch'
  difficulty: 'easy' | 'normal' | 'hard'
}

export interface ScoreRecord {
  score: number
  distance: number
  date: Date
}

export interface GameStats {
  totalScore: number
  totalDistance: number
  totalCoins: number
  gamesPlayed: number
  achievementsUnlocked: number
}

export const useGameStore = defineStore('game', () => {
  // Game state
  const gameStatus = ref<'menu' | 'playing' | 'paused' | 'gameOver'>('menu')
  const currentScore = ref(0)
  const currentDistance = ref(0)
  const currentLevel = ref(1)
  const lives = ref(3)

  // Settings
  const settings = ref<GameSettings>({
    soundEnabled: true,
    musicEnabled: true,
    masterVolume: 80,
    controlScheme: 'keyboard',
    difficulty: 'normal'
  })

  // Character system
  const characterManager = new CharacterManager()

  // Game statistics
  const gameStats = ref<GameStats>({
    totalScore: 0,
    totalDistance: 0,
    totalCoins: 0,
    gamesPlayed: 0,
    achievementsUnlocked: 0
  })

  // Score records
  const scoreRecords = ref<ScoreRecord[]>([])

  // Computed properties
  const characters = computed(() => characterManager.getAllCharacters())
  const unlockedCharacters = computed(() => characterManager.getUnlockedCharacters())
  const selectedCharacter = computed(() => characterManager.getSelectedCharacter())

  const highScore = computed(() => 
    scoreRecords.value.length > 0 
      ? Math.max(...scoreRecords.value.map(record => record.score))
      : 0
  )

  const bestDistance = computed(() => 
    scoreRecords.value.length > 0 
      ? Math.max(...scoreRecords.value.map(record => record.distance))
      : 0
  )

  // Actions
  const startGame = () => {
    gameStatus.value = 'playing'
    currentScore.value = 0
    currentDistance.value = 0
    lives.value = 3
  }

  const pauseGame = () => {
    if (gameStatus.value === 'playing') {
      gameStatus.value = 'paused'
    }
  }

  const resumeGame = () => {
    if (gameStatus.value === 'paused') {
      gameStatus.value = 'playing'
    }
  }

  const endGame = () => {
    gameStatus.value = 'gameOver'
    // Save score record
    scoreRecords.value.push({
      score: currentScore.value,
      distance: currentDistance.value,
      date: new Date()
    })
    // Sort by score descending
    scoreRecords.value.sort((a, b) => b.score - a.score)
    // Keep only top 10 scores
    if (scoreRecords.value.length > 10) {
      scoreRecords.value = scoreRecords.value.slice(0, 10)
    }
    saveToLocalStorage()
  }

  const resetGame = () => {
    gameStatus.value = 'menu'
    currentScore.value = 0
    currentDistance.value = 0
    currentLevel.value = 1
    lives.value = 3
  }

  const updateScore = (points: number) => {
    currentScore.value += points
  }

  const updateDistance = (distance: number) => {
    currentDistance.value = distance
  }

  const selectCharacter = (characterId: string) => {
    if (characterManager.selectCharacter(characterId)) {
      saveToLocalStorage()
    }
  }

  const unlockCharacter = (characterId: string) => {
    if (characterManager.unlockCharacter(characterId)) {
      saveToLocalStorage()
    }
  }

  const checkCharacterUnlocks = () => {
    const newlyUnlocked = characterManager.checkUnlockConditions(gameStats.value)
    if (newlyUnlocked.length > 0) {
      saveToLocalStorage()
      return newlyUnlocked
    }
    return []
  }

  const updateGameStats = (score: number, distance: number, coins: number) => {
    gameStats.value.totalScore += score
    gameStats.value.totalDistance += distance
    gameStats.value.totalCoins += coins
    gameStats.value.gamesPlayed += 1
    
    // Update character stats
    const currentChar = characterManager.getSelectedCharacter()
    if (currentChar) {
      characterManager.updateCharacterStats(currentChar.id, score, distance)
    }
    
    // Check for new unlocks
    checkCharacterUnlocks()
    saveToLocalStorage()
  }

  const updateSettings = (newSettings: Partial<GameSettings>) => {
    settings.value = { ...settings.value, ...newSettings }
    saveToLocalStorage()
  }

  const resetSettings = () => {
    settings.value = {
      soundEnabled: true,
      musicEnabled: true,
      masterVolume: 80,
      controlScheme: 'keyboard',
      difficulty: 'normal'
    }
    saveToLocalStorage()
  }

  // Local storage functions
  const saveToLocalStorage = () => {
    const gameData = {
      settings: settings.value,
      characterManager: characterManager.serialize(),
      gameStats: gameStats.value,
      scoreRecords: scoreRecords.value
    }
    localStorage.setItem('vue-parkour-game', JSON.stringify(gameData))
  }

  const loadFromLocalStorage = () => {
    try {
      const savedData = localStorage.getItem('vue-parkour-game')
      if (savedData) {
        const gameData = JSON.parse(savedData)
        if (gameData.settings) {
          settings.value = { ...settings.value, ...gameData.settings }
        }
        if (gameData.characterManager) {
          characterManager.deserialize(gameData.characterManager)
        }
        if (gameData.gameStats) {
          gameStats.value = { ...gameStats.value, ...gameData.gameStats }
        }
        if (gameData.scoreRecords) {
          scoreRecords.value = gameData.scoreRecords.map((record: any) => ({
            ...record,
            date: new Date(record.date)
          }))
        }
      }
    } catch (error) {
      console.error('Failed to load game data from localStorage:', error)
    }
  }

  // Initialize from localStorage
  loadFromLocalStorage()

  return {
    // State
    gameStatus,
    currentScore,
    currentDistance,
    currentLevel,
    lives,
    settings,
    characters,
    unlockedCharacters,
    selectedCharacter,
    scoreRecords,
    gameStats,
    
    // Computed
    highScore,
    bestDistance,
    
    // Actions
    startGame,
    pauseGame,
    resumeGame,
    endGame,
    resetGame,
    updateScore,
    updateDistance,
    selectCharacter,
    unlockCharacter,
    checkCharacterUnlocks,
    updateGameStats,
    updateSettings,
    resetSettings,
    saveToLocalStorage,
    loadFromLocalStorage,
    
    // Character manager access
    characterManager
  }
})